#include "./sq-stack.h"
#include <iostream>

void initStack(SqStack &stack)
{
	stack.base = (ElemType *)malloc(MAX_SIZE * sizeof(ElemType));
	stack.top = stack.base;
	stack.stackSize = MAX_SIZE;
}

int stackEmpty(SqStack &stack)
{
	return stack.base == stack.top;
}

int stackLength(SqStack &stack)
{
	return stack.top - stack.base;
}

ElemType getTop(SqStack &stack)
{
	if (stackEmpty(stack))
	{
		return 0;
	}
	return *(stack.top - 1);
}

void push(SqStack &stack, ElemType e)
{
	// 如果栈满了就再追加10个元素的空间
	if (stack.top - stack.base >= stack.stackSize)
	{
		stack.base = (ElemType *)realloc(stack.base, (stack.stackSize + 10) * sizeof(ElemType));
		// 重置顶指针
		stack.top = stack.base + stack.stackSize;
		stack.stackSize += 10;
	}
	*stack.top = e;
	stack.top++;
}

ElemType pop(SqStack &stack)
{
	if (stackEmpty(stack))
	{
		return 0;
	}
	ElemType e = *(stack.top - 1);
	stack.top--;
	return e;
}

void StackTraverse(SqStack &stack, void (*visit)(ElemType &e))
{
	ElemType *pointer = stack.base;
	while (pointer != stack.top)
	{
		visit(*pointer);
		pointer++;
	}
}